package com.cangxuan.app.ui.user;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.*;
import androidx.constraintlayout.widget.ConstraintLayout;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cangxuan.app.R;
import com.cangxuan.app.entity.Goods;
import com.cangxuan.app.entity.Registration;
import com.cangxuan.app.entity.UserGoods;
import com.cangxuan.app.ui.BaseActivity;
import com.cangxuan.app.ui.collection.CollectionDetailActivity;
import com.cangxuan.app.ui.collection.OrderPayActivity;
import com.cangxuan.app.utils.DeviceUtils;
import com.cangxuan.app.utils.HttpUtils;

import java.io.File;
import java.io.Serializable;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Author: 陈青石
 * Activity: 我的藏品页面
 * Layout: activity_mycollection
 */
public class MyCollectionActivity extends BaseActivity {
    GridView myCollectionGridView;

    Button myCollectionCollection;
    Button myCollectionBlindBox;

    class MyCollectionAdapter extends BaseAdapter {

        private List<UserGoods> userGoodsList;

        public MyCollectionAdapter(List<UserGoods> userGoodsList) {
            this.userGoodsList = userGoodsList;
        }

        @Override
        public int getCount() {
            return userGoodsList.size();
        }

        @Override
        public Object getItem(int i) {
            return userGoodsList.get(i);
        }

        @Override
        public long getItemId(int i) {
            return userGoodsList.get(i).getId();
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {

            MyCollectionViewHolder viewHolder;
            if (view == null) {
                view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.activity_mycollection_gridview_item, viewGroup, false);
                viewHolder = new MyCollectionViewHolder(view);
                view.setTag(viewHolder);
            } else {
                viewHolder = (MyCollectionViewHolder) view.getTag();
            }
            UserGoods userGoods = userGoodsList.get(i);



            String goodsImagePath = "/data/data/" + getApplicationContext().getPackageName() + userGoods.getImage();
            File imageFile = new File(goodsImagePath);
            if (imageFile.exists()) {
                viewHolder.myCollectionItemImg.setImageBitmap(BitmapFactory.decodeFile(goodsImagePath));
            } else {
                Thread thread = new Thread(() -> {
                    boolean result = HttpUtils.download(userGoods.getImage(), goodsImagePath);
                    if (result) {
                        handler.post(() -> {
                            viewHolder.myCollectionItemImg.setImageBitmap(BitmapFactory.decodeFile(goodsImagePath));
                        });
                    }
                });
                thread.start();
            }

            LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(width, width);
            viewHolder.myCollectionItemImg.setLayoutParams(param);
            System.out.println(width+"-----");

            viewHolder.myCollectionItemName.setText(userGoods.getName());
            viewHolder.myCollectionCode.setText("NO." + userGoods.getGoodsId());
            viewHolder.myCollectionSeries.setText("数量:" + userGoods.getCount());
            return view;
        }

        /**
         * 视图持有类，
         * 该类的属性会包含ListView的项里面需要动态设置值的控件
         */
        class MyCollectionViewHolder {
            ImageView myCollectionItemImg;
            TextView myCollectionItemName;
            TextView myCollectionCode;
            TextView myCollectionSeries;

            public MyCollectionViewHolder(View view) {
                this.myCollectionItemImg = view.findViewById(R.id.mycollection_item_img);
                this.myCollectionItemName = view.findViewById(R.id.mycollection_item_name);
                this.myCollectionCode = view.findViewById(R.id.mycollection_code);
                this.myCollectionSeries = view.findViewById(R.id.mycollection_series);
            }

        }

    }


    int index = 0;

    MyCollectionAdapter myCollectionAdapter;

    List<UserGoods> goodsLists;

    LinearLayout myCollectionLoading;
    LinearLayout emptyText;
    Map<String, String> header;
    Handler handler = new Handler();
    int width;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mycollection);
        setTitle("我的藏品");

        WindowManager wm = this.getWindowManager();
        width = (wm.getDefaultDisplay().getWidth()-140)/2;

        header = new HashMap<>();
        header.put("Authorization", DeviceUtils.getDeviceID());

        myCollectionCollection = findViewById(R.id.mycollection_collection);
        myCollectionBlindBox = findViewById(R.id.mycollection_blind_box);
        myCollectionGridView = findViewById(R.id.mycollection_gridview);
        myCollectionLoading = findViewById(R.id.mycollection_loading);
        emptyText = findViewById(R.id.empty_text);
        myCollectionGridView.setColumnWidth(width);


        myCollectionCollection.setOnClickListener(view -> {
            if (index != 0) {
                initData();
                index = 0;
                replaceBar();
            }
        });

        myCollectionBlindBox.setOnClickListener(view -> {
            if (index != 1) {
                initData();
                index = 1;
                replaceBar();
            }
        });


        initData();

        replaceBar();

        myCollectionGridView.setOnItemClickListener((adapterView, view, i, l) -> {
            Intent intent = new Intent();
            intent.setClass(getApplicationContext(), CollectionDetailActivity.class);
            intent.putExtra("goodsId", goodsLists.get(i).getGoodsId());
            intent.putExtra("isShow", 0);
            startActivity(intent);
        });


    }

    private void initData() {
        myCollectionGridView.setVisibility(View.GONE);
        emptyText.setVisibility(View.GONE);
        myCollectionLoading.setVisibility(View.VISIBLE);
        Thread thread = new Thread(() -> {
            String jsonString = HttpUtils.get("/api/user/goods/get", header);
            JSONObject jsonResponse = JSONObject.parseObject(jsonString);
            if (jsonResponse.getInteger("status") == HttpURLConnection.HTTP_OK) {
                JSONArray jsonArray = jsonResponse.getJSONArray("value");
                goodsLists = JSONObject.parseArray(jsonArray.toJSONString(), UserGoods.class);
                handler.post(() -> {
                    myCollectionLoading.setVisibility(View.GONE);
                    if (goodsLists.size() == 0) {
                        emptyText.setVisibility(View.VISIBLE);
                    } else {
                        myCollectionGridView.setVisibility(View.VISIBLE);
                    }
                    myCollectionAdapter = new MyCollectionAdapter(goodsLists);
                    myCollectionGridView.setAdapter(myCollectionAdapter);
                });
            } else {
                handler.post(() -> {
                    myCollectionGridView.setVisibility(View.VISIBLE);
                    emptyText.setVisibility(View.GONE);
                    myCollectionLoading.setVisibility(View.GONE);
                    Toast.makeText(getApplicationContext(), jsonResponse.getString("message"), Toast.LENGTH_SHORT).show();
                });
            }
        });
        thread.start();

    }



    private void replaceBar() {
        if (index == 0) {
            myCollectionCollection.setBackground(getResources().getDrawable(R.drawable.shape_mycollection_btn_live));
            myCollectionCollection.setTextColor(getResources().getColor(R.color.white));
            myCollectionBlindBox.setBackground(getResources().getDrawable(R.drawable.shape_mycollection_btn_normal));
            myCollectionBlindBox.setTextColor(getResources().getColor(R.color.black));
        } else {
            myCollectionBlindBox.setBackground(getResources().getDrawable(R.drawable.shape_mycollection_btn_live));
            myCollectionBlindBox.setTextColor(getResources().getColor(R.color.white));
            myCollectionCollection.setBackground(getResources().getDrawable(R.drawable.shape_mycollection_btn_normal));
            myCollectionCollection.setTextColor(getResources().getColor(R.color.black));
        }
    }
}
